package com.corticon.dialogs.dao.hibernate;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Repository;

import com.corticon.dialogs.dao.UiControlDAO;
import com.corticon.dialogs.model.UiControl;
import com.corticon.dialogs.util.Pager;

@Repository("uiControlDAO")
public class UiControlHibernateDAO extends GenericHibernateDAO<UiControl, String> implements
    UiControlDAO {

    private String countByUserGroup =
        "select count(*) from Uicontrol uicontrol where uicontrol.userGroup.name='ALL' or uicontrol.userGroup.name = :userGroup";
    private String countByUserGroupAll =
        "select count(*) from Uicontrol uicontrol where uicontrol.userGroup.name=" + "'ALL'";
    private String queryByUserGroup =
        "from Uicontrol uicontrol where uicontrol.userGroup.name = :userGroup or uicontrol.userGroup.name=" + "'ALL'";
    private String queryByUserGroupAll =
        "from Uicontrol uicontrol where uicontrol.userGroup.name = 'ALL'";

    @Override
    public long getCountByUserGroup(String userGroup) {
        return (Long) getSession().createQuery(countByUserGroup).setParameter("userGroup",
            userGroup).uniqueResult();
    }

    @Override
    public List<UiControl> findPageByUserGroup(String userGroup, Pager pager) {
        List<UiControl> uicontrols = new ArrayList<UiControl>();

        uicontrols = getSession().createQuery(queryByUserGroup).setParameter("userGroup", userGroup).
            setFirstResult(pager.getFirstRecord()).setMaxResults(pager.getPageSize()).list();

        return uicontrols;
    }

    @Override
    public long getCountByUserGroupAll(String userGroup) {
        return (Long) getSession().createQuery(countByUserGroupAll).uniqueResult();
    }

    @Override
    public List<UiControl> findPageByUserGroupAll(String userGroup, Pager pager) {
        List<UiControl> uicontrols = new ArrayList<UiControl>();

        uicontrols = getSession().createQuery(queryByUserGroupAll).
            setFirstResult(pager.getFirstRecord()).setMaxResults(pager.getPageSize()).list();

        return uicontrols;
    }
}

